package com.codelazy.desetalk;

import java.util.Arrays;
import java.util.LinkedList;

import com.capricorn.ArcLayout;
import com.capricorn.ArcMenu;
import com.desetalk.proto.ResponseProtocol.Response;
import com.desetalk.proto.ResponseProtocol.Room;
import com.desetalk.proto.ResponseProtocol.User;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.liyh.widget.PullToRefreshListView;
import com.liyh.widget.PullToRefreshListView.OnRefreshListener;

public class LobbyFragment extends ListFragment {
	String TAG;
	private ImageView fastin;
	private LinkedList<String> mListItems;
	private BroadcastReceiver mMessageReceiver;
	private Response response;
	private static final int[] ITEM_DRAWABLES = { R.drawable.create_room,
			R.drawable.search_room, R.drawable.fresh_room };

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_lobby, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		ArcMenu arcMenu = (ArcMenu) getView().findViewById(R.id.arc_menu);
		initArcMenu(arcMenu, ITEM_DRAWABLES);

		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					@Override
					public void onRefresh() {
						// Do work to refresh the list here.
						sendCmd("enterLobby 28");
					}
				});

		mListItems = new LinkedList<String>();
		mListItems.addAll(Arrays.asList(mStrings));

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, mListItems);

		setListAdapter(adapter);

		fastin = (ImageView) getActivity().findViewById(R.id.fastin);
		fastin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendCmd("enterLobby 28");
			}
		});
		mMessageReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				// Get extra data included in the Intent
				response = (Response) intent.getSerializableExtra("message");
				mListItems.clear();
				if (response.hasLobby()) {
					// 大厅
					for (Room room : response.getLobby().getRoomList()) {
						mListItems.add("房间信息：房间号：" + room.getId() + "，房主id："
								+ room.getOwnerId() + "，课程id："
								+ room.getCourseId() + "，用户个数："
								+ room.getUserCount() + "，房间状态："
								+ (room.getState() ? "学习未开始" : "学习进行中"));
						for (User user : room.getUserList()) {
							System.out.println("用户信息：id：" + user.getId()
									+ "，用户名：" + user.getName() + "，头像："
									+ user.getFigureUrl() + "，准备状态："
									+ (user.getReady() ? "已准备" : "未准备"));
						}
					}
					((PullToRefreshListView) getListView()).onRefreshComplete();
				} else if (response.hasUserNum()) {
					// 人数
					System.out.println(response.getUserNum());
				} else if (response.hasCreateRoom()) {
					// 创建房间返回信息
					if (response.getCreateRoom().getSuccess()) {
						Toast.makeText(getActivity(), "房间创建成功，房间号为："
								+ response.getCreateRoom().getRoomId(),
								Toast.LENGTH_SHORT).show();
						sendCmd("entryRoom "+response.getCreateRoom().getRoomId()+" 28");

					} else {
						Toast.makeText(getActivity(),"房间创建失败！",
								Toast.LENGTH_SHORT).show();
					}
				}
				else if (response.hasEnterRoom()) {
		    		// 加入房间返回信息
		    		if(response.getEnterRoom().getSuccess()){
						Toast.makeText(getActivity(),"加入房间成功",
								Toast.LENGTH_SHORT).show();
						Intent intentt = new Intent(getActivity(),
								RoomActivity.class);
						intentt.putExtra("name", "liyh");
						startActivity(intentt);
		    			//printRoomInfo(response.getEnterRoom().getRoom());
		    		} else {
						Toast.makeText(getActivity(),"加入房间失败",
								Toast.LENGTH_SHORT).show();
		    		}
		    	}
				
			}
		};
		LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
				mMessageReceiver, new IntentFilter("local_receiver"));
	}

	private void initArcMenu(ArcMenu menu, int[] itemDrawables) {
		final int itemCount = itemDrawables.length;
		for (int i = 0; i < itemCount; i++) {
			ImageView item = new ImageView(getActivity());
			item.setImageResource(itemDrawables[i]);

			final int position = i;
			menu.addItem(item, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (position == 0) {// 创建房间
						sendCmd("createRoom 28");
					} else if (position == 1) {// 查找房间

					} else if (position == 2) {// 刷新房间
						sendCmd("enterLobby 28");
					}
					Toast.makeText(getActivity(), "position:" + position,
							Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	private void sendCmd(String cmd) {
		Intent intent = new Intent("local_sender");
		// You can also include some extra data.
		intent.putExtra("cmd", cmd);
		LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
	}

	private String[] mStrings = {};
}
